﻿#ifndef PST_DOUBLESPINBOX_H
#define PST_DOUBLESPINBOX_H

#include "EDoubleSpinBox.h"
#include "API_BaseWidget.h"

namespace BaseWidget
{
    // a class for a customized QDoubleSpinBox
    class API_BASEWIDGET DoubleSpinBox : public EDoubleSpinBox
    {
        Q_OBJECT
    public:
        // constructor.
        explicit DoubleSpinBox(QWidget* pQParent = nullptr) : EDoubleSpinBox(pQParent)
        {
            this->setDecimals(9);
            this->setMinimum(-1000000000);
            this->setMaximum(1000000000);
        }
        // destructor.
        virtual ~DoubleSpinBox() = default;
        // disabled:
        DoubleSpinBox(const DoubleSpinBox&) = delete;
        DoubleSpinBox& operator=(const DoubleSpinBox&) = delete;

    public:
        /* converts value from text.
         *
         * Overloaded to process accepted input correctly.
         */
        virtual double valueFromText(const QString& text) const override
        {
            auto s = text;
            s.remove(",");
            bool ok = false;
            double value = locale().toDouble(s, &ok);
            return ok ? value : QDoubleSpinBox::value();
        }

        QString textFromValue(double value) const override
        {
            return (QLocale().toString(value, 'g', QLocale::FloatingPointShortest)).remove(",");
        }

        virtual QString valueAsQString() const
        {
            return (QLocale().toString(this->value(), 'g', QLocale::FloatingPointShortest)).remove(",");
        }

    protected:

        ///* determines whether input is valid.
        // *
        // * Overloaded to change accepted input.
        // */
        virtual QValidator::State validate(QString& text, int& pos) const override
        {
            if (text.isEmpty())
            {
                return QValidator::Acceptable;
            }
            if (text.contains(",") || text.contains("-") || text.contains("e"))
            {
                return QValidator::Acceptable;
            }
            bool ok = false;
            locale().toDouble(text, &ok);
            return ok ? QValidator::Acceptable : QValidator::Invalid;
        }

    };
}
#endif
